﻿
@{
    ViewBag.Title = "购物车";
    Layout = "~/Views/Shared/_MallLayout.cshtml";
    string img_url = ViewBag.img_url;
}
@model cart_info_dto
@{ var count = Model.cartitems.Count;}
<link href="~/Content/css/tokenmall/css/reg.css" rel="stylesheet" />
<body class="page-confirmOrder page-shoppingCart @(count>0?"":"page-nothing") ">


    <!--header end -->
    @if (count == 0) {
        <div class="nothing">
            <div class="box fn-center">
                <div class="img">
                    <img src="/Content/css/tokenmall/img/nothing.png" />
                </div>
                <p class="fn26 col-gray mb30">您的购物车是空的！</p>
                <p>
                    <a href="javascript:void(0)" class="ui-btn ui-btn-border" id="gohome">去 购 物</a>
                </p>
            </div>
        </div>
    }
    <div class="mod-shoppingCart checkList lt-mb">
        @if (count > 0) {
            foreach (var item in Model.cartitems) {
                if (item.products.Count > 0) {
                    <div class="item">
                        <div class="topShop">
                            <span class="checkBox">
                                <input class="icon-check checkAllItem" type="checkbox" name="checkAllItem">
                            </span>

                            @if (item.shop.shop_id == 0) {
                                <i class="icon-search3"></i>
                                <a class="fn28 name" href="/DistributionMall/index">
                                    <span class="mr20">拓垦官方旗舰店</span>
                                    <i class="icon-go4"></i>
                                </a>

                            } else {
                                if (!string.IsNullOrEmpty(item.shop.logo)) {
                                    <i class="icon-search3" style="background-image:url(@(img_url + item.shop.logo))"></i>

                                } else {
                                    <i class="icon-search3"></i>
                                }

                                <a class="fn28 name" href="/DistributionMall/index2?shopId=@item.shop.shop_id">
                                    <span class="mr20">@item.shop.shop_name</span>
                                    <i class="icon-go4"></i>
                                </a>

                            }
                            <i class="icon-delete fn-right"></i>
                        </div>
                        @foreach (var product in item.products) {
                            <div class="content">
                                <div class="innerCon fn-left">
                                    <div class="flex">
                                        <span class="checkBox">
                                            <input class="icon-check" type="checkbox" name="checkListItem" data-id="@product.cart_id" data-max="@product.product_stock" data-shop-id="@item.shop.shop_id" data-skuid="@product.sku_id" data-product-id="@product.product_id" data-merchant-no="@product.merchant_no">
                                        </span>
                                        <div class="img" onclick="javascript: location.href='/DistributionMall/ProductDetail?productId=@product.product_id&merchant_no=@product.merchant_no'">
                                            <img src="@product.product_main_img" />
                                        </div>
                                        <div class="text flex-1">
                                            <div class="tit fn-nowrap2 fn26 mb10" onclick="javascript: location.href='/DistributionMall/ProductDetail?productId=@product.product_id&merchant_no=@product.merchant_no'">
                                                @product.product_name
                                            </div>
                                            <p class="col-gray fn26 size mb10"> @product.product_sku_name</p>
                                            <div class="price">
                                                @if (product.price > 0) {
                                                    <em class="col-red fn22">￥</em><span class="col-red fn28 itemPrice">@product.price.ToString("0.##")</span>
                                                } else {
                                                    <span class="itemPrice" style="display:none;">@product.price.ToString("0.##")</span>
                                                }

                                                @if (product.price > 0 && product.activity_red_drill > 0) {
                                                    <span class="col-red">+</span>
                                                }

                                                @if (product.activity_red_drill > 0) {
                                                    <span class="col-red fn28 itemRedDrill">@product.activity_red_drill.ToString("0.######")</span><em class="col-red fn22">红钻</em>
                                                } else {
                                                    <span class="itemRedDrill" style="display:none">@product.activity_red_drill.ToString("0.######")</span>
                                                }

                                                <input class="totalLi" type="hidden" value="@product.price.ToString("0.##")">
                                                <input class="totalLiRedDrill" type="hidden" value="@product.activity_red_drill.ToString("0.######")">
                                                <div class="num">
                                                    <span class="min">-</span>
                                                    <input class="text_box" name="" type="text" value="@product.num" readonly data-id="@product.cart_id" data-max="@product.product_stock" unselectable="on" onfocus="this.blur()">
                                                    <span class="add">+</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <span class="delete fn30" data-id="@product.cart_id">
                                    删除
                                </span>
                            </div>
                        }


                    </div>
                }
            }
        }
        @if (Model.products.Count > 0) {
            <div class="item" id="invalid">
                <div class="topShop mb-30">
                    <span class="firstDiv col-gray">失效宝贝 @Model.products.Count 件</span>
                    <span class="fn-right col-red" id="removeInvalid">清空失效宝贝</span>
                </div>
                @foreach (var product in Model.products) {
                    <div class="content" data-id="@product.cart_id">
                        <div class="innerCon fn-left">
                            <div class="flex">
                                <span class="checkBox">
                                    <em class="shixiao flex-box">
                                        失效
                                    </em>
                                </span>
                                <div class="img" onclick="javascript: location.href='/DistributionMall/ProductDetail?productId=@product.product_id&merchant_no=@product.merchant_no'">
                                    <img src="@product.product_main_img" />
                                </div>
                                <div class="text flex-1" onclick="javascript: location.href='/DistributionMall/ProductDetail?productId=@product.product_id&merchant_no=@product.merchant_no'">
                                    <div class="tit fn-nowrap2 fn26 mb10">
                                        @product.product_name
                                    </div>
                                    <div class="fn30">
                                        库存不足或商品已下架
                                    </div>

                                </div>
                            </div>
                        </div>
                        <span class="delete fn30" data-id="@product.cart_id">
                            删除
                        </span>
                    </div>


                }

            </div>
        }


        <div class="col-gray fn-center">
            没有更多了~~~
        </div>
    </div>


    <div class="lt-bottom shadow">
        <span class="checkBox"><input class="icon-check allselect" type="checkbox" name="1"></span>
        <div class="right fn-right" id="totalBox">
            <span class="fn28 mr20">
                总金额:
                <span id="total_cash_span">
                    <em class="col-red fn24">￥</em><em class="col-red fn32 fn-pfBold" id="total">0</em>
                </span>
                <span id="total_add_span" class="col-red">+</span>
                <span id="total_red_drill_span">
                    <em class="col-red fn32 fn-pfBold" id="totalRedDrill">0</em><em class="col-red fn24">红钻</em>
                </span>
                &nbsp;
            </span>
            <a href="javascript:;" class="ui-btn ui-btn-big ui-btn-red" id="buyNow">
                购买(<em class="fn24 shuliang">0</em>)
            </a>
        </div>
        <div class="right fn-right none" id="deleteBox">
            <a href="javascript:;" class="ui-btn ui-btn-border w140 mr20" id="remove">删除<span class="fn22">(<em class="shuliang">0</em>)</span></a>
            <a href="javascript:;" class="ui-btn ui-btn-borderRed w140 j-complete">完成</a>
        </div>
    </div>
    <script src="~/Scripts/token-common.js?v=001"></script>
    <script type="text/javascript">
        $(function () {
            $("#gohome").click(function () {
                try {
                    if (browser.versions.ios) {
                        window.webkit.messageHandlers.gohome.postMessage('111');
                    } else if (browser.versions.android) {
                        androidfuntion.gohome();
                    }
                } catch (e) {
                    location.href = '/DistributionMall/index';

                }

            });
            $(document).ready(function () {
                //首先获取导航栏距离浏览器顶部的高度
                // var top = $('.lt-head').offset().top;
                //开始监控滚动栏scroll
                $(document).scroll(function () {
                    //获取当前滚动栏scroll的高度并赋值
                    var scrTop = $(window).scrollTop();
                    //开始判断如果导航栏距离顶部的高度等于当前滚动栏的高度则开启悬浮
                    if (scrTop > 0) {
                        $('.lt-head').addClass('shoppingBg');
                    } else {//否则清空悬浮
                        $('.lt-head').removeClass('shoppingBg');
                    }
                })
            })
            var cartids = [];
            // 全选
            $(".allselect").click(function () {

                if ($(this).attr("checked")) {
                    $(".checkList input[type=checkbox]").each(function () {
                        $(this).attr("checked", true);
                        // $(this).next().css({ "background-color": "#3366cc", "color": "#ffffff" });
                    });
                    GetCount();

                }
                else {
                    $(".checkList input[type=checkbox]").each(function () {
                        if ($(this).attr("checked")) {
                            $(this).attr("checked", false);
                            //$(this).next().css({ "background-color": "#ffffff", "color": "#000000" });
                        } else {
                            $(this).attr("checked", true);
                            //$(this).next().css({ "background-color": "#3366cc", "color": "#000000" });
                        }
                    });
                    GetCount();

                }

                setTotal();
            });
            //全选 订单
            $('.checkAllItem').click(function () {
                var is_all_check = true;
                $("input[name=checkAllItem]").each(function (i, item) {
                    if (!$(item).is(':checked')) {
                        is_all_check = false;
                    }
                })
                if (is_all_check) { $('.allselect').attr("checked", true); }
                else {
                    $('.allselect').attr("checked", false);
                }
                if ($(this).attr("checked")) {
                    $(this).parents('.item').find("input[name=checkListItem]").each(function () {
                        $(this).attr("checked", true);
                        // $(this).next().css({ "background-color": "#3366cc", "color": "#ffffff" });
                    });
                    GetCount();
                    setTotal();

                }
                else {
                    $(this).parents('.item').find("input[name=checkListItem]").each(function () {
                        if ($(this).attr("checked")) {
                            $(this).attr("checked", false);
                            //$(this).next().css({ "background-color": "#ffffff", "color": "#000000" });
                        } else {
                            $(this).attr("checked", true);
                        }
                    });
                    GetCount();
                    setTotal();
                }

            })

            //单选框
            $(".item").each(function () {
                var oSelf = $(this);
                oSelf.find("input[name='checkListItem']").on('change', function () {
                    if (oSelf.find("input[name='checkListItem']").not("input:checked").size() <= 0) {
                        oSelf.find(".checkAllItem").attr("checked", true);
                    } else {
                        oSelf.find(".checkAllItem").attr("checked", false);
                    }
                    setTotal();
                });
            });

            // 输出
            $(".item input[name=checkListItem]").click(function () {
                var is_all_check = true;
                $("input[name=checkListItem]").each(function (i, item) {
                    if (!$(item).is(':checked')) {
                        is_all_check = false;
                    }
                })
                if (is_all_check) { $('.allselect').attr("checked", true); }
                else {
                    $('.allselect').attr("checked", false);
                }
                GetCount();
                setTotal();
            });
            var flag = false;
            $("#buyNow").click(function () {
                if (flag) return;
                flag = true;
                var data = [];
                $("input[name=checkListItem]").each(function (i, item) {
                    var that = $(item);
                    if (that.attr("checked")) {
                        var obj = {};
                        obj.product_id = that.attr("data-product-id");
                        obj.merchant_no = that.attr("data-merchant-no");
                        obj.sku_id = that.attr("data-skuid");
                        obj.shop_id = that.attr("data-shop-id");
                        obj.num = that.parents('.content').find('input[class*=text_box]').val();
                        //ojb.distribution_shop_id = that.attr("data-distribution-shop-id");
                        data.push(obj);
                    }
                });
                if (data.length == 0) {
                    layer.msg("请选择商品");
                    return;
                }
                $.post("/order/AddBuy", {
                    model: data,
                    type: 1
                }, function (result) {
                    flag = false;
                    if (result.result_code == 1000) {
                        window.location.href = '/Order/ConfirmOrder';
                    }
                    else {
                        layer.msg(result.result_msg);
                    }
                });
            });
            // 数量总和
            function GetCount() {
                var conts = 0;
                var aa = 0;
                $("input[name=checkListItem]").each(function () {
                    if ($(this).attr("checked")) {
                        for (var i = 0; i < $(this).length; i++) {
                            conts += parseFloat($(this).val());
                            aa += 1;
                        }
                    }
                });
                $(".shuliang").text(aa);
                //$("#total").html((conts).toFixed(2));
            }

            // 计算合计
            function setTotal() {
                // var len = $(".itemPrice");
                var sum = 0;
                var sumRedDrill = 0;
                $("input[name=checkListItem]:checked").each(function () {
                    var len = $(this).parents('.content').find('.totalLi').val();
                    sum += parseFloat(len);
                    var lenRed = $(this).parents('.content').find('.totalLiRedDrill').val();
                    sumRedDrill += parseFloat(lenRed);
                });
                $("#total").text(toDecimalRoundNoZero(parseFloat(sum), 2));
                $("#totalRedDrill").text(toDecimalRoundNoZero(parseFloat(sumRedDrill), 6));

                if (sum > 0 || (sum == 0 && sumRedDrill == 0)) {
                    $("#total_cash_span").show();
                } else {
                    $("#total_cash_span").hide();
                }

                if (sum > 0 && sumRedDrill > 0) {
                    $("#total_add_span").show();
                } else {
                    $("#total_add_span").hide();
                }

                if (sumRedDrill > 0) {
                    $("#total_red_drill_span").show();
                } else {
                    $("#total_red_drill_span").hide();
                }

            }
            setTotal();


            $(".add").click(function () {
                var that = $(this);
                var t = that.parent('.num').find('input[class*=text_box]');
                var cartid = t.attr("data-id")
                if (parseInt(t.val()) + 1 > t.attr("data-max")) {
                    layer.msg("数量超出范围");
                    return;
                }
                $.post("/cart/UpdateCart", { cart_id: cartid, type: 1 }, function (result) {
                    if (result.result_code == 1000) {
                        t.val(parseInt(t.val()) + 1);
                        that.parents('.price').find('.j-quantity').text(parseInt(t.val()));
                        numTotal();
                        setTotal();
                    }
                    else {
                        layer.msg(result.result_msg);
                        if (result.result_code == 1001) {
                            location.reload();
                        }
                        else if (result.result_code == 1002) {
                        }
                    }
                });

            })
            $(".min").click(function () {
                var that = $(this);
                var t = that.parent().find('input[class*=text_box]');
                var cartid = t.attr("data-id")
                if (parseInt(t.val()) - 1 <= 0) return;
                $.post("/cart/UpdateCart", { cart_id: cartid, type: 0 }, function (result) {
                    if (result.result_code == 1000) {
                        t.val(parseInt(t.val()) - 1);
                        that.parents('.price').find('.j-quantity').text(parseInt(t.val()));
                        numTotal();
                        setTotal();
                    }
                    else {
                        layer.msg(result.result_msg);
                        if (result.result_code == 1001) {
                            window.location.reload();
                        }
                        else if (result.result_code == 1002) {
                        }
                    }
                });

            })

            function numTotal() {
                var s = 0;
                var r = 0;
                $(".item .content").each(function () {
                    // console.log($(this).find('input[class*=text_box]').val())
                    s = parseFloat($(this).find('input[class*=text_box]').val()) * parseFloat($(this).find('span[class*=itemPrice]').text());
                    r = parseFloat($(this).find('input[class*=text_box]').val()) * parseFloat($(this).find('span[class*=itemRedDrill]').text());
                    // console.log(s);
                    $(this).find(".totalLi").val(s);
                    $(this).find(".totalLiRedDrill").val(r);

                });

            }

            numTotal();




            // 点击编辑
            $('.edit').click(function () {
                $(this).toggleClass('cur');
                if ($(this).hasClass('cur')) {
                    $(this).text('完成');
                    $('#totalBox,.quantity').addClass('none');
                    $('#deleteBox,.num').removeClass('none');

                } else {
                    $(this).text('编辑');
                    $('#totalBox,.quantity').removeClass('none');
                    $('#deleteBox,.num').addClass('none');
                }
            })

            // 点击完成
            $('.j-complete').click(function () {
                $('#totalBox,.quantity').removeClass('none');
                $('#deleteBox,.num').addClass('none');
                $('.edit').removeClass('cur').text('编辑');
            })
            //删除失效商品
            $("#removeInvalid").click(function () {
                var invalids = [];
                $("#invalid").find('.content').each(function (i, item) {
                    var id = $(item).attr("data-id");
                    invalids.push(id);
                });
                if (invalids.length == 0) { layer.msg("没有失效商品"); return; }
                swal(
                    {
                        title: "",
                        text: "确定要清空失效商品吗？",
                        type: "warning",
                        showCancelButton: true,
                        closeOnConfirm: false,
                        cancelButtonText: "取消",
                        confirmButtonText: '确定'
                    },
                    function (isConfirm) {
                        if (isConfirm) {
                            $.post("/cart/DelCart", { ids: invalids }, function (result) {
                                if (result.result_code == 1000) {
                                    window.location.reload();
                                }
                                else {
                                    layer.msg(result.result_mgs);
                                }
                            });

                        }
                    }
                );
            });
            // 点击删除
            $('#remove').click(function () {
                cartids = [];
                $("input[name=checkListItem]:checked").each(function (i, item) {
                    var id = $(item).attr("data-id");
                    cartids.push(id);

                });
                if (cartids.length <= 0) {
                    layer.msg("请选择商品");
                    return;
                }
                swal(
                    {
                        title: "",
                        text: "确定要删除吗？",
                        type: "warning",
                        showCancelButton: true,
                        closeOnConfirm: false,
                        cancelButtonText: "取消",
                        confirmButtonText: '确定'
                    },
                    function (isConfirm) {
                        if (isConfirm) {
                            $.post("/cart/DelCart", { ids: cartids }, function (result) {
                                if (result.result_code == 1000) {
                                    window.location.reload();
                                    //swal({
                                    //    title: "",
                                    //    text: "删除成功",
                                    //    type: "success",
                                    //    showCancelButton: true,
                                    //    closeOnConfirm: false,
                                    //    cancelButtonText: "返回",
                                    //    confirmButtonText: '确定'
                                    //})
                                }
                                else {
                                    layer.msg(result.result_mgs);
                                }
                            });

                        }
                    }
                );

            })
            function removeItem() {
                $("input[name=checkAllItem]:checked").each(function () {
                    var len = $(this).parents('.item').remove();

                });
            }
            function removeContent() {
                $("input[name=checkListItem]:checked").each(function () {
                    var len = $(this).parents('.content').remove();

                });
            }

            $('.delete').click(function () {
                var cartids = [];
                cartids.push($(this).attr("data-id"));
                swal(
                    {
                        title: "",
                        text: "确定要删除吗？",
                        type: "warning",
                        showCancelButton: true,
                        closeOnConfirm: false,
                        cancelButtonText: "取消",
                        confirmButtonText: '确定'
                    },
                    function (isConfirm) {
                        if (isConfirm) {
                            $.post("/cart/DelCart", { ids: cartids }, function (result) {
                                if (result.result_code == 1000) {
                                    window.location.reload();
                                }
                                else {
                                    layer.msg(result.result_mgs);
                                }
                            });

                        }
                    }
                );


            })

            $('.icon-delete').click(function () {
                var cartids = [];
                // var len = $(this).parents('.item').find('.content').length;
                $(this).parents('.item').children('.content').find("input[name='checkListItem']").each(function (i, item) {
                    cartids.push($(item).attr("data-id"));

                })
                if (cartids.length <= 0) {
                    layer.msg("请选择商品");
                    return;
                }
                swal(
                    {
                        title: "",
                        text: "确定要删除吗？",
                        type: "warning",
                        showCancelButton: true,
                        closeOnConfirm: false,
                        cancelButtonText: "取消",
                        confirmButtonText: '确定'
                    },
                    function (isConfirm) {
                        if (isConfirm) {
                            $.post("/cart/DelCart", { ids: cartids }, function (result) {
                                if (result.result_code == 1000) {
                                    location.reload();
                                }
                                else {
                                    layer.msg(result.result_mgs);
                                }
                            });

                        }
                    })
            })

        })
    </script>
    <script type="text/javascript">
        $(document).ready(function (e) {
            // 删除按钮的宽度
            var widthLeft = $('.delete').width();



            // 设定每一行的宽度=屏幕宽度+按钮宽度
            $(".item .content").width($(".mod-shoppingCart .item").width() + $(".delete").width() + 2);
            // 设定常规信息区域宽度=屏幕宽度
            $(".innerCon").width($(".mod-shoppingCart .item").width());

            $(".item .content .delete").addClass("cur");
            // 获取所有行，对每一行设置监听
            var lines = $(".innerCon");
            var len = lines.length;
            var lastX, lastXForMobile;

            // 用于记录被按下的对象
            var pressedObj;  // 当前左滑的对象
            var lastLeftObj; // 上一个左滑的对象

            // 用于记录按下的点
            var start;

            // 网页在移动端运行时的监听
            for (var i = 0; i < len; ++i) {
                lines[i].addEventListener('touchstart', function (e) {
                    lastXForMobile = e.changedTouches[0].pageX;
                    pressedObj = this; // 记录被按下的对象

                    // 记录开始按下时的点
                    var touches = event.touches[0];
                    start = {
                        x: touches.pageX, // 横坐标
                        y: touches.pageY  // 纵坐标
                    };
                });

                lines[i].addEventListener('touchmove', function (e) {
                    // 计算划动过程中x和y的变化量
                    var touches = event.touches[0];
                    delta = {
                        x: touches.pageX - start.x,
                        y: touches.pageY - start.y
                    };

                    // 横向位移大于纵向位移，阻止纵向滚动
                    if (Math.abs(delta.x) > Math.abs(delta.y)) {
                        event.preventDefault();
                    }
                });

                lines[i].addEventListener('touchend', function (e) {
                    if (lastLeftObj && pressedObj != lastLeftObj) { // 点击除当前左滑对象之外的任意其他位置
                        $(lastLeftObj).animate({ marginLeft: "0" }, 200); // 右滑
                        lastLeftObj = null; // 清空上一个左滑的对象
                    }
                    var diffX = e.changedTouches[0].pageX - lastXForMobile;
                    if (diffX < -50) {
                        $(pressedObj).animate({ marginLeft: -widthLeft }, 200); // 左滑
                        lastLeftObj && lastLeftObj != pressedObj &&
                            $(lastLeftObj).animate({ marginLeft: "0" }, 200); // 已经左滑状态的按钮右滑
                        lastLeftObj = pressedObj; // 记录上一个左滑的对象
                    } else if (diffX > 50) {
                        if (pressedObj == lastLeftObj) {
                            $(pressedObj).animate({ marginLeft: "0" }, 200); // 右滑
                            lastLeftObj = null; // 清空上一个左滑的对象
                        }
                    }
                });
            }

            // 网页在PC浏览器中运行时的监听
            for (var i = 0; i < len; ++i) {
                $(lines[i]).bind('mousedown', function (e) {
                    lastX = e.clientX;
                    pressedObj = this; // 记录被按下的对象
                });

                $(lines[i]).bind('mouseup', function (e) {
                    if (lastLeftObj && pressedObj != lastLeftObj) { // 点击除当前左滑对象之外的任意其他位置
                        $(lastLeftObj).animate({ marginLeft: "0" }, 200); // 右滑
                        lastLeftObj = null; // 清空上一个左滑的对象
                    }
                    var diffX = e.clientX - lastX;
                    if (diffX < -50) {
                        $(pressedObj).animate({ marginLeft: widthLeft }, 200); // 左滑
                        lastLeftObj && lastLeftObj != pressedObj &&
                            $(lastLeftObj).animate({ marginLeft: "0" }, 200); // 已经左滑状态的按钮右滑
                        lastLeftObj = pressedObj; // 记录上一个左滑的对象
                    } else if (diffX > 50) {
                        if (pressedObj == lastLeftObj) {
                            $(pressedObj).animate({ marginLeft: "0" }, 200); // 右滑
                            lastLeftObj = null; // 清空上一个左滑的对象
                        }
                    }
                });
            }
        });



    </script>
</body>

